<template>
	<view class="box">
		<view class="wrap">
			<scroll-view scroll-y class="chat" :scroll-top="scrollTop">
				<view class="list">
					<view class="chat-news" v-for="(item,index) in list" :key="index">
						<!-- 根据角色判断 -->
						<block v-if="item.role === 'me'">
							<!-- 自己的消息显示在右侧 -->
							<view class="news-lf">
								<text class="new-txt">{{item.content}}</text>
								<image class="new-img" :src="userMsg.userAvatar"></image>
							</view>
						</block>
						<!-- 对方的消息显示在左侧 -->
						<block v-else>
							<view>
								<image class="new-img" :src="userMsg.friendAvatar"></image>
								<text class="new-txt">{{item.content}}</text>
							</view>
						</block>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- 聊天输入 -->
		<view class="message" :class="{ 'keyboard-open': keyboardOpenClass === 'keyboard-open' }">
			<uni-easyinput type="text" cursor-spacing="20" placeholder="请输入聊天内容…" v-model="message"
				@focus="handleInputFocus" @blur="handleInputBlur"></uni-easyinput>
			<image :src="selectedImageSrc" style="width: 80rpx; height: 80rpx ;margin-left: 30rpx;" mode="aspectFill"
				@click="sendMessage">
			</image>
		</view>
	</view>

</template>

<script>
	import {
		sendMessageTo,
		getUser
	} from "@/api/message";
	import config from '@/config';

	export default {
		data() {
			return {
				scrollTop: 0,
				list: [],
				id: 0,
				connected: false,
				password: '123',
				token: '', // 新增字段，存储登录成功后的token或唯一标识
				socketTask: null,

				// url: "",
				message: "", // 发送的内容
				text_content: "",
				ws: null,
				friendId: 1, // 用于传给后端,聊天的对象
				userId: 1, // 当前用户的userId,用于建立连接时拼接

				selectedImageSrc: "/static/img/healthPage/voice.png",
				imageSrc: ["/static/img/healthPage/voice.png", "/static/img/healthPage/send.png"],

				userMsg: {
					friendAvatar: "",
					userAvatar: ""
				}
			};
		},
		onLoad(option) {
			console.log(option.userId);
			this.friendId = option.userId // 存储friendId
			// 存储userId到前端中
			this.storeUser(this.friendId)
		},
		// 使用watch监听message的变化
		watch: {
			message(newVal) {
				if (newVal !== '') {
					this.selectedImageSrc = this.imageSrc[1]; // 当输入框内容不为空时，切换图片路径
				} else {
					this.selectedImageSrc = this.imageSrc[0]; // 当输入框内容为空时，恢复初始图片路径
				}
			},
		},
		onUnload() {
			wx.closeSocket();
			console.log('连接已断开');
		},
		methods: {
			startWebSocketConnection() {
				// url: 'ws://192.168.77.32:8080/websocket/message/' + this.userId
				this.socketTask = wx.connectSocket({
					url: config.wsUrl + this.userId
				});
				this.connected = true

				this.socketTask.onOpen(res => {
					console.log('WebSocket连接成功');
					this.connected = true;
				});
				this.socketTask.onClose(() => {
					console.log('WebSocket连接已断开');
					this.connected = false;
				});
				// 接收服务器发来的消息
				this.socketTask.onMessage((msg) => {
					console.log('WebSocket消息已收到');
					console.log(msg);

					// 接收传来的信息
					if (msg.data) {
						const data = JSON.parse(msg.data); //{fromName: "zs", isSystem: false, message: "dwada"}
						this.list.push({
							id: this.id++,
							content: data.message,
							role: "Other",
						});
						this.scrollTop = 9999; // 设置滚动条始终在底部
						this.message = '';
						this.$forceUpdate();
					}
				})

			},

			sendMessage() {
				if (this.message && this.connected) {
					var msg = {
						"friendId": this.friendId,
						"message": this.message
					}
					sendMessageTo(msg).then(response => {
						console.log(response);
						console.log(response.data);
						this.contentList = response.data
						this.loading = false
					})
					// 显示自己的信息
					this.list.push({
						id: this.id++,
						content: this.message,
						role: "me",
					});

					this.scrollTop = 9999;
					this.message = '';

				} else {
					wx.showToast({
						title: '尚未连接或消息不能为空',
						icon: 'none',
						duration: 2000,
					});
				}
			},

			// 获取useId、avatar
			storeUser(friendId) {
				getUser(friendId).then(response => {
					console.log(response.data);
					this.userMsg.friendAvatar = response.data.friendAvatar
					this.userMsg.userAvatar = response.data.userAvatar
					this.userId = response.data.userId
					// 获取到后开启WebSocket连接
					this.startWebSocketConnection();
				})
			},

			handleInputFocus() {
				this.keyboardHeight = 300; // 假设值
				this.$nextTick(() => this.adjustMessagePosition());
			},
			handleInputBlur() {
				this.keyboardHeight = 0;
				this.$nextTick(() => this.adjustMessagePosition());
			},
			adjustMessagePosition() {
				if (this.keyboardHeight > 0) {
					this.keyboardOpenClass = 'keyboard-open';
				} else {
					this.keyboardOpenClass = '';
				}
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #f7f7f7;
		height: 100%;
	}

	.chat {
		padding: 5rpx 10rpx;
		font-size: 14px;
		line-height: 80rpx;
		word-break: break-all;
		margin-bottom: 100rpx;
		box-sizing: border-box;
	}

	.wrap {
		height: 100%;
		width: 100%;
		display: flex;
		border-top: 0px;
		box-sizing: border-box;
	}

	/* 聊天 */

	.chat-news {
		width: 100%;
		overflow: hidden;
	}

	.news-lf {
		float: right;
		padding-right: 20rpx;
	}

	.chat-news::after {
		display: block;
		height: 0;
		clear: both;
		content: ‘’;
	}

	.new-rl {
		float: left;
		padding-left: 20rpx;
	}

	.new-img {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		vertical-align: middle;
		margin-right: 10rpx;
	}

	.new-txt {
		max-width: 300rpx;
		display: inline-block;
		border-radius: 6rpx;
		line-height: 40rpx;
		background-color: lightgreen;
		padding: 5rpx 20rpx;
		margin: 0 10rpx;
		margin-left: 50rpx;
	}

	.new-text {
		margin-left: 0;
		background: lightgreen;
	}

	.message {
		width: 100%;
		height: 100rpx;
		position: fixed;
		background-color: #fff;
		bottom: 0;
		left: 50%;

		transform: translateX(-50%);
		border-top: 2rpx solid #eee;
		border-radius: 15rpx;
		box-sizing: border-box;
		z-index: 3;

		display: flex;
		align-items: center;
		justify-content: space-between;

		.uni-easyinput.input {
			height: 50rpx;
			flex-grow: 1;
		}
	}
</style>